import { Component, OnInit, Host } from "@angular/core";
import { IpLoginService } from "../ip-login.service";
import { AppComponent } from "../../../../app.component";
import { ActivatedRoute } from "@angular/router";
import { IpListModel, IpDataModel } from "../models/ipList.model";
import * as cloneDeep from 'lodash/cloneDeep';
import { ToasterService } from "angular2-toaster";

@Component({
    templateUrl: './ipList.component.html',
    styleUrls: ['./ipList.component.scss'],
    providers: [IpLoginService]
})
export class IpListComponent implements OnInit {
    public pattern: string = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
    public accountName: string;
    public ipList: IpListModel;
    private prevList: IpListModel;

    constructor(
        @Host() private rootComponent: AppComponent,
        private route: ActivatedRoute,
        private loginService: IpLoginService,
        private toasterService: ToasterService) { }

    ngOnInit() {
        this.route.params.subscribe(params => {
            this.accountName = params['name'];
            this.loginService.getIpList(params['id']).subscribe(data => {
                if (data)
                    this.ipList = data;
                else
                    this.ipList = new IpListModel(this.accountName, params['id'], []);

                this.prevList = cloneDeep(this.ipList);
                this.rootComponent.finishLoading();
            });
        });
    }

    public add() {
        this.ipList.ipDatas.push(new IpDataModel('', ''));
    }

    public save() {
        this.loginService.setIpList(this.ipList).subscribe(data => {
            if (data)
                this.toasterService.pop('success', 'Success', 'IP list has been saved.');
            else
                this.toasterService.pop('warning', 'Warning', 'IP list has not been saved.');
        });
    }

    public remove(element: IpDataModel) {
        this.ipList.ipDatas.splice(this.ipList.ipDatas.indexOf(element), 1);
    }

    public cancel(event: any) { 
        this.ipList = cloneDeep(this.prevList);
        event.preventDefault();
    }
}